// pages/o2oLocation_loc/o2oLocation_loc.js
var QQMapWX = require("../../../mymap/qqmap-wx-jssdk.min.js");
var location = require("../../../mybehaviors/location/location");
var qqmapsdk;
var app = getApp();
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    suggestion: [],
    address_latitude: "",
    address_longitude: "",
    markers: [],
    address_detail: "",
    suggestionshow: false,
    mksData: [],
    mapmessageData: {
      title: "",
      message: "",
      latitude: "",
      longitude: "",
      city: "",
    },
    scaleData: 16,
    tag: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id,
      });
    }
    if (options.store_id) {
      this.setData({
        store_id: options.store_id,
        form: JSON.parse(options.form),
        create: options.create,
      });
    }
    if (!app.globalData.qqmapkey) {
      app._getTemplate().then((res) => {
        qqmapsdk = new QQMapWX({
          key: app.globalData.qqmapkey,
        });
        if (options.tag) {
          this.setData({
            tag: options.tag,
          });
        }
        this.poscurrent();
      });
    } else {
      qqmapsdk = new QQMapWX({
        key: app.globalData.qqmapkey,
      });
      if (options.tag) {
        this.setData({
          tag: options.tag,
        });
      }
      this.poscurrent();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  searchconfirmbtn(e) {
    var val = e.detail.value;
    this.addressinp(val);
  },
  addressinpbtn(e) {
    var val = e.detail.value;
    this.addressinp(val);
  },
  addressinp(val) {
    var _this = this;
    if (!val) {
      this.setData({
        suggestionshow: false,
      });
      return;
    }
    //调用关键词提示接口
    qqmapsdk.getSuggestion({
      //获取输入框值并设置keyword参数
      keyword: val, //用户输入的关键词，可设置固定值,如keyword:'KFC'
      //region:'北京', //设置城市名，限制关键词所示的地域范围，非必填参数
      sig: app.globalData.qqmapsig,
      success: function (res) {
        //搜索成功后的回调
        var sug = [];
        for (var i = 0; i < res.data.length; i++) {
          sug.push({
            // 获取返回结果，放到sug数组中
            title: res.data[i].title,
            id: res.data[i].id,
            addr: res.data[i].address,
            city: res.data[i].city,
            district: res.data[i].district,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng,
          });
        }
        _this.setData({
          //设置suggestion属性，将关键词搜索结果以列表形式展示
          suggestion: sug,
          suggestionshow: true,
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {},
    });
  },
  //数据回填方法
  backfill: function (e) {
    var id = e.currentTarget.id;
    for (var i = 0; i < this.data.suggestion.length; i++) {
      if (i == id) {
        this.setData({
          address_detail: this.data.suggestion[i].title,
          address_latitude: this.data.suggestion[i].latitude,
          address_longitude: this.data.suggestion[i].longitude,
          "mapmessageData.title": this.data.suggestion[i].title,
          "mapmessageData.message": this.data.suggestion[i].addr,
          "mapmessageData.latitude": this.data.suggestion[i].latitude,
          "mapmessageData.longitude": this.data.suggestion[i].longitude,
          "mapmessageData.city": this.data.suggestion[i].city,
          suggestionshow: false,
        });
        this.nearby_search();
      }
    }
  },
  // 事件触发，调用接口
  nearby_search: function () {
    var _this = this;
    // 调用接口
    qqmapsdk.search({
      keyword: this.data.address_detail, //搜索关键词
      location: {
        latitude: this.data.address_latitude,
        longitude: this.data.address_longitude,
      }, //设置周边搜索中心点
      sig: app.globalData.qqmapsig,
      success: function (res) {
        //搜索成功后的回调
        console.log("ccccc", res);
        var mks = [];
        var mksData = [];
        for (var i = 0; i < res.data.length; i++) {
          mks.push({
            // 获取返回结果，放到mks数组中
            title: res.data[i].title,
            id: res.data[i].id,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng,
            iconPath: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", //图标路径
            width: 20,
            height: 25,
            callout: {
              padding: "10rpx",
              borderRadius: "5rpx",
              content: res.data[i].title,
            },
          });
          mksData.push({
            address: res.data[i].address,
            title: res.data[i].title,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng,
            id: res.data[i].id,
            city: res.data[i].ad_info.city
              ? res.data[i].ad_info.city
              : res.res.data[i].ad_info.province,
          });
        }
        _this.setData({
          //设置markers属性，将搜索结果显示在地图中
          markers: mks,
          mksData: mksData,
        });
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      },
    });
  },
  getmarkertap(e) {
    let markerId = e.markerId;
    for (var i = 0; i < this.data.mksData.length; i++) {
      let id = this.data.mksData[i].id;
      if (markerId == id) {
        this.setData({
          "mapmessageData.title": this.data.mksData[i].title,
          "mapmessageData.message": this.data.mksData[i].address,
          "mapmessageData.latitude": this.data.mksData[i].latitude,
          "mapmessageData.longitude": this.data.mksData[i].longitude,
          "mapmessageData.city": this.data.mksData[i].city,
        });
      }
    }
  },
  addbtn() {
    let mapCtx = wx.createMapContext("myMap");
    let that = this;
    mapCtx.getScale({
      success: function (e) {
        let scale = e.scale;
        that.setData({
          scaleData: scale + 1,
        });
      },
    });
  },
  minusbtn() {
    let mapCtx = wx.createMapContext("myMap");
    let that = this;
    mapCtx.getScale({
      success: function (e) {
        let scale = e.scale;
        that.setData({
          scaleData: scale - 1,
        });
      },
    });
  },
  addressplay() {
    this.poscurrent();
  },
  poscurrent: function () {
    let that = this;
    wx.getSetting({
      success(resData) {
        if (!resData.authSetting["scope.userLocation"]) {
          wx.authorize({
            scope: "scope.userLocation",
            success() {},
            fail(msgData) {},
            complete() {
              that.getlocaldata();
            },
          });
        }else{
          that.getlocaldata();
        }
      },
    });

  },
  getlocaldata() {
    this._getLocation((mapdata, e) => {
      this.setData({
        address_detail: "",
        address_latitude: mapdata.location.lat,
        address_longitude: mapdata.location.lng,
        "mapmessageData.title": mapdata.formatted_addresses.recommend,
        "mapmessageData.address_component": mapdata.formatted_addresses,
        "mapmessageData.message": mapdata.address,
        "mapmessageData.latitude": mapdata.location.lat,
        "mapmessageData.longitude": mapdata.location.lng,
        "mapmessageData.city": mapdata.address_component.city
          ? mapdata.address_component.city
          : mapdata.address_component.province,
      });
    });
  },
  buttonbtn() {
    var prevPage;
    var pages;
    let point = {
      lat: this.data.address_latitude,
      lng: this.data.address_longitude,
    };
    console.log(this.data.mapmessageData, point, "point");
    wx.setStorage({
      key: "address-point",
      data: {
        point: point,
        city: this.data.mapmessageData.city,
        address_component: this.data.mapmessageData.address_component
      },
    });
    if (this.data.tag == "hotel") {
      wx.reLaunch({
        url:
          "/packageC/hotel/HotelIndex/HotelIndex?addressData=" +
          JSON.stringify(this.data.mapmessageData),
      });
    } else if (this.data.tag == 'coffee'){
      wx.redirectTo({
        url: '/packageJ/coffee_machine/coffee_machine_nearby/coffee_machine_nearby',
      })
    } else if (this.data.tag == "home") {
      wx.reLaunch({
        url:
          "/packageG/index/index?addressData=" +
          JSON.stringify(this.data.mapmessageData),
      });
    } else if (this.data.tag == "easyRefuel") {
      wx.reLaunch({
        url: "/packageD/easyRefuel/easyRefuel",
      });
    } else if (this.data.tag == "storeConsume") {
      wx.reLaunch({
        url:
          "/packageH/o2o/storeConsumeIndex/storeConsumeIndex?id=" +
          this.data.id,
      });
    } else if (this.data.tag == "cake") {
      wx.reLaunch({
        url:
          "/packageF/sachertorte/sachertorteIndex/sachertorteIndex?city=" +
          this.data.mapmessageData.city,
      });
    } else if (this.data.tag == "appointment") {
      console.log(this.data.mapmessageData);
      let point = {
        lat: this.data.mapmessageData.latitude,
        lng: this.data.mapmessageData.longitude,
      };
      let pos = {
        address: this.data.mapmessageData.message,
        city: this.data.mapmessageData.city,
        title: this.data.mapmessageData.title,
        point: point,
      };
      pages = getCurrentPages();
      prevPage = pages[pages.length - 3]; //上一个页面    -3就是上上一个页面
      prevPage.setData({
        //本页面数据赋值到上一个页面
        pos,
      });
      wx.navigateBack({
        delta: 2,
      });
    } else if (this.data.tag == "diy") {
      let urls = wx.getStorageSync("diyurl");
      wx.reLaunch({
        url: urls,
      });
    } else if (this.data.tag == "activityHome") {
      wx.reLaunch({
        url:
          "/packageC/Myshaky/activityHome/activityHome?city=" +
          this.data.mapmessageData.city,
      });
    } else if (this.data.tag == "store") {
      wx.navigateTo({
        url:
          "/packageD/buy/myOrder_v2/myOrder_v2?tag=" +
          this.data.tag +
          "&store_id=" +
          this.data.store_id +
          "&form=" +
          JSON.stringify(this.data.form) +
          "&create=" +
          this.data.create +
          "&is_point=" +
          JSON.stringify(point),
      });
    } else if (this.data.tag == "storeApply"||this.data.tag == "selfCarryApply") {
      try {
        wx.setStorageSync("applyaddresspoint", {
          address: this.data.mapmessageData.message,
          point: point,
          city: this.data.mapmessageData.city,
        });
        wx.navigateBack({
          delta: 1,
          fail() {},
        });
      } catch (e) {
        console.log(e);
      }
    } else if(this.data.tag == "communityStore" || this.data.tag == "communityStoreDetails"){
      let point = {
        lat: this.data.mapmessageData.latitude,
        lng: this.data.mapmessageData.longitude,
      };
      let pos = {
        address: this.data.mapmessageData.message,
        city: this.data.mapmessageData.city,
        title: this.data.mapmessageData.title,
        point: point,
      };
      pages = getCurrentPages();
      prevPage = pages[pages.length - 3]; //上一个页面    -3就是上上一个页面
      prevPage.setData(
        //本页面数据赋值到上一个页面
        pos
      );
      prevPage._getData();
      wx.navigateBack({
        delta: 2,
      });
    } else if(this.data.tag.indexOf("project_verification")!==-1){
      wx.setStorage({
        key: "address-point",
        data: { point: { lat: this.data.mapmessageData.latitude, lng: this.data.mapmessageData.longitude }, city: this.data.mapmessageData.message, address_component: this.data.mapmessageData.address_component }
      });
      switch(this.data.tag){
      case "project_verification/MyProject":
        wx.reLaunch({
          url: '/packageH/project_verification/MyProject/MyProject?location_change=1',
        });
        break;
      case "project_verification/VerificationProjectList":
        wx.reLaunch({
          url: '/packageH/project_verification/VerificationProjectList/VerificationProjectList?location_change=1',
        });
        break;
      }
    } else if(this.data.tag == "suppligoodsOrde"){
      wx.navigateBack({
        delta: 1
      });
    } else if(this.data.tag == "tagCloud"){
      wx.navigateBack({
        delta: 2
      });
    } else {
      wx.reLaunch({
        url:
          "/packageC/o2o/o2oHome/o2oHome?addressData=" +
          JSON.stringify(this.data.mapmessageData),
      });
    }
  },
});
